package es.ats.codington.festival.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContext;
import es.ats.codington.festival.exceptions.DAOException;

public class FERSDataConnection {
	private Connection con;
	private static final FERSJsonReader reader=new FERSJsonReader("src/es/ats/codington/festival/utils/DbConstants.json");
	//ServletContext
	private ServletContext context;
	
	public FERSDataConnection() {
		super();
		this.setContext(null);
	}
	
	public FERSDataConnection(Connection con) {
		super();
		this.setCon(con);
	}
	
	public Connection connect() throws DAOException{
		try {
			Class.forName(reader.readString("driver")).newInstance();
			setCon(DriverManager.getConnection(reader.readString("connectionUrl"), reader.readString("connectionUser"), reader.readString("connectionPassword")));
			return this.con;		
		}
		catch (Exception ex) {
			throw new DAOException("DB connection failure:"+ex.getMessage(), ex);
		}
		
	}
	
	public void disconnect() throws DAOException{
		try {
			con.close();
		}
		catch (Exception ex) {
			throw new DAOException("DB disconnection failure:"+ex.getMessage(), ex);
		}
	}
	
	//ServletContext connection;
	public FERSDataConnection(ServletContext context) {		
		connect();
		this.setContext(context);
	}
	
	public Statement createStatement() throws SQLException{
		return con.createStatement();
	}
	
	public PreparedStatement prepareStatement(String str) throws SQLException{
		return con.prepareStatement(str);
	}

	public Connection getCon() {
		return con;
	}

	public void setCon(Connection con) {
		this.con = con;
	}

	public static FERSJsonReader getReader() {
		return reader;
	}

	public ServletContext getContext() {
		return context;
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}
	
	
}
